package org.testtools.handler;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Map;

import org.testtools.connector.impl.HTTPConnector;

public class HTTPHandler {

    public static final String RESPONSE_MESSAGE = "response-message";

    public static final String RESPONSE_CODE = "response-code";

    public static final String RESPONSE_PAYLOAD = "response-payload";

    private final HTTPConnector connector;

    // TODO JUnit
    public HTTPHandler(String url) {
        connector = new HTTPConnector(url, null, null);
    }

    // TODO JUnit
    public HTTPHandler(String url, String contentType, String method) {
        connector = new HTTPConnector(url, contentType, method);
    }

    // TODO JUnit
    public Map<String, String> doRequest(final String content) throws IOException {
        final HttpURLConnection conn = connector.getConnection();

        try {
            return doRequest(conn, content);
        } finally {
            conn.disconnect();
        }
    }

    // TODO JUnit
    public static Map<String, String> doRequest(final HttpURLConnection conn, final String content) throws IOException {
        final Map<String, String> response = new HashMap<String, String>();
        final StringBuilder sb = new StringBuilder();

        try {
            final Writer wout = new OutputStreamWriter(conn.getOutputStream());
            wout.write(content);
            wout.flush();
            wout.close();

            final BufferedInputStream input = new BufferedInputStream(conn.getInputStream());
            for (int character = input.read(); character != -1; character = input.read()) {
                sb.append((char) character);
            }

            input.close();
            sb.trimToSize();
        }

        catch (Exception e) {
            e.printStackTrace();
        }

        finally {
            response.put(RESPONSE_PAYLOAD, sb.toString());
            response.put(RESPONSE_CODE, String.valueOf(conn.getResponseCode()));
            response.put(RESPONSE_MESSAGE, conn.getResponseMessage());
        }

        return response;
    }
}
